<template>
  <a-modal :visible="show" :title="taskName + '的策略'" @cancel="cancel" :width="1500" :footer="null">
    <div style="margin-bottom: 20px;">
      <a-button type="primary" @click="addStrategieStatic">
        添加策略
      </a-button>
      <a-tooltip style="margin-left: 10px;">
        <template slot="title">
          1.空耗策略：设置账户计划消耗达到 x 元时，且成单是 0 时，且商品点击按钮点击次数小于等于w 时执行关闭计划的策略。<br>
          2.拓量策略：设置账户计划成单数达到 m 时，执行复制 n 条计划的策略。如果是放量计划，系统直接复制为控成本计划，出价为实际成本。如果是控成本计划，复制的计划出价为原始计划出价下降1-3%（按n随机分布）<br>
          3.控成本策略：设置成单数量>=1 的计划，成本超过 t 时，可以关闭并复制 n 条的策略。复制的计划结构按拓量策略执行。<br>
          4.预算策略：当该计划的消耗达到了计划预算的50%，且没有关停，就直接扩100%预算。<br>
          5.极限策略：设置计划成单数达到1时，就关闭计划，并复制p条计划。复制策略参加拓量策略。<br>
          6.批量提价：每天晚上 2 点开始系统批量处理，当天未出单的，在投控成本计划，百分比上调出价参数。一旦触及上限则不再调整，上限是该账户控成本出价最高的那条计划的出价。<br>
          7.暂停策略：超过n天不出单则关闭计划。<br>
          8.点击率策略：允许针对 M 以上点击率的计划，在消耗在 Y 的时候，关闭计划，并复制一条。<br>
          9.清理策略：批量删除已暂停的计划。<br>
        </template>
        <a-icon type="info-circle" />
      </a-tooltip>  
    </div>

    <StandardTable 
      class="customTable"
      :dataSource="dataSource" 
      :columns="columns" 
      :loading="loading"
      :pagination="{showTotal:total => `共 ${total} 条数据`, pageSize: pageSize,showLessItems: true, showSizeChanger:true,pageSizeOptions:['10', '20', '50', '100']}"
      >
      <div slot="account" slot-scope="{record}" >
        <div v-if="record.xmod == 'normal'">
          <a-tooltip>
            <template slot="title">
              {{record.account}}
            </template>
            <span class="line1" style="width: 180px;cursor: pointer;">{{record.account}}</span>
          </a-tooltip>
        </div>
        <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
          <a-select
            mode="multiple"
            :maxTagCount="2"
            v-model="record.accountArr"
            style="width: 100%;"
            @change="accountSelect(record.key)"
            @search="accountSelectSearch"
          >
            <a-select-option :value="item.account" v-for="(item, index) in accountList" :key="index">
              {{ item.account }}
            </a-select-option>
          </a-select>
        </div>
      </div>
      <div slot="campaign_type" slot-scope="{record}" >
        <div v-if="record.xmod == 'normal'">
          {{ setCampaign_type(record.campaign_type) }}
        </div>
        <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
          <a-select v-model="record.campaign_type" style="width: 120px" >
            <a-select-option :value="-1">
              全部计划
            </a-select-option>
            <a-select-option :value="1">
              放量计划
            </a-select-option>
            <a-select-option :value="4">
              控成本计划
            </a-select-option>
          </a-select>
        </div>
      </div>
      <div slot="type" slot-scope="{record}" >
        <div v-if="record.xmod == 'normal'">
          {{ setType(record.type) }}
        </div>
        <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
          <a-select v-model="record.type" style="width: 120px" >
            <a-select-option :value="1">
              空耗策略
            </a-select-option>
            <a-select-option :value="2">
              拓量策略
            </a-select-option>
            <a-select-option :value="3">
              控成本策略
            </a-select-option>
            <a-select-option :value="4">
              预算策略
            </a-select-option>
            <a-select-option :value="5">
              极限策略
            </a-select-option>
            <a-select-option :value="6">
              批量提价
            </a-select-option>
            <!-- <a-select-option :value="7">
              笛卡尔策略
            </a-select-option> -->
            <a-select-option :value="7">
              暂停策略
            </a-select-option>
            <a-select-option :value="8">
              点击率策略
            </a-select-option>
            <a-select-option :value="9">
              自动清理策略
            </a-select-option>
          </a-select>
        </div>
      </div>
      <div slot="status" slot-scope="{record}">
        <div style="display:flex;align-items: center;" v-if="record.xmod == 'normal'">
          <div style="width:6px;height:6px;border-radius:50%;background-color:#ff7875" v-if="record.status==0"></div>
          <div style="width:6px;height:6px;border-radius:50%;background-color:#00cc63" v-else></div>
          <span style="margin-left:5px">{{record.status | setStatus}}</span>
        </div>
        <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
          <a-switch :checked="record.status == 1?true:false" @change="(status) => status ? record.status = 1 : record.status = 0" />
        </div>
      </div>
      <div slot="cost" slot-scope="{record}">
        <div v-if="record.type == 1 || record.type == 8">
          <span v-if="record.xmod == 'normal'">{{ record.content.cost }}</span>
          <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
            <a-input-number v-model="record.content.cost" :min="0" />
          </div>
        </div>
        <span v-else>-</span>
      </div>
      <div slot="w" slot-scope="{record}">
        <div v-if="record.type == 1">
          <span v-if="record.xmod == 'normal'">{{ record.content.w }}</span>
          <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
            <a-input-number v-model="record.content.w" :min="0" />
          </div>
        </div>
        <span v-else>-</span>
      </div>
      <div slot="m" slot-scope="{record}">
        <div v-if="record.type == 2" >
          <span v-if="record.xmod == 'normal'">{{ record.content.m }}</span>
          <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
            <a-input-number v-model="record.content.m" :min="0" />
          </div>
        </div>
        <span v-else>-</span>
      </div>
      <div slot="ctr" slot-scope="{record}">
        <div v-if="record.type == 8" >
          <span v-if="record.xmod == 'normal'">{{ record.content.ctr }}</span>
          <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
            <a-input-number v-model="record.content.ctr" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
          </div>
        </div>
        <span v-else>-</span>
      </div>
      <div slot="t" slot-scope="{record}">
        <div v-if="record.type == 3" >
          <span v-if="record.xmod == 'normal'">{{ record.content.t }}</span>
          <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
            <a-input-number v-model="record.content.t" :min="0" />
          </div>
        </div>
        <span v-else>-</span>
      </div>
      <div slot="day" slot-scope="{record}">
        <div v-if="record.type == 7" >
          <span v-if="record.xmod == 'normal'">{{ record.content.day }}</span>
          <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
            <a-input-number v-model="record.content.day" :min="0" />
          </div>
        </div>
        <span v-else>-</span>
      </div>
      <div slot="n" slot-scope="{record}">
        <div v-if="record.type == 2 || record.type == 3 || record.type == 5">
          <span v-if="record.xmod == 'normal'">{{ record.content.n }}</span>
          <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
            <a-input-number v-model="record.content.n" :min="0" />
          </div>
        </div>
        <span v-else>-</span>
      </div>
      <div slot="g" slot-scope="{record}">
        <div v-if="record.type == 2 || record.type == 3 || record.type == 5 || record.type == 6">
          <span v-if="record.xmod == 'normal'">{{ record.content.g }}</span>
          <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
            <a-input-number v-model="record.content.g"/>
          </div>
        </div>
        <span v-else>-</span>
      </div>
      <div slot="action" slot-scope="{record}" >
        <div v-if="record.xmod == 'normal'">
          <a style="margin-right: 8px" href="javascript:;" @click="edit(record.key)">
            <a-icon type="edit"/>
            <span style="margin-left: 2px;">编辑</span>
          </a>
          <a-popconfirm title="确定删除？" ok-text="删除" cancel-text="取消" @confirm="deleteStrategie(record.id, record.task_id)">
            <a-button type="link" style="padding: 0;">
              <a-icon type="delete" /> 
              <span style="margin-left: 2px;">删除</span>
            </a-button>
          </a-popconfirm>
        </div>
        <div v-else-if="record.xmod == 'add' || record.xmod == 'edit'">
          <a-popconfirm title="确定保存？" ok-text="保存" cancel-text="取消" style="margin-right: 8px" @confirm="save(record.key)">
            <a-button type="link" style="padding: 0;">
              <a-icon type="save" /> 
              <span style="margin-left: 2px;">保存</span>
            </a-button>
          </a-popconfirm>
          <a href="javascript:;">
            <a-icon type="delete"/>
            <span style="margin-left: 2px;" @click="close(record.key)">取消</span>
          </a>
        </div>
      </div>
    </StandardTable>
  </a-modal>
</template>

<script>
import {strategies,addStrategy,updateStrategy,delStrategy} from '@/api/dianshang/dianshang'
import StandardTable from '@/components/table/StandardTable'
import {getAllBdAccountList} from '@/api/xinxiliu/account'

export default {
  props: {
    show: Boolean,
    taskId: [String, Number],
    taskName: String,
  },
  data() {
    return {
      dataSource: [],
      loading: false,
      pageSize: 10,
      columns: [
        {
          title: '类型',
          width: 100,
          dataIndex: 'type',
          scopedSlots: {
            customRender: 'type'
          },
        },
        // {
        //   title: '账户',
        //   dataIndex: 'account',
        //   width:200,
        //   scopedSlots: {
        //     customRender: 'account'
        //   },
        // },
        {
          title: '计划作用域',
          width: 120,
          dataIndex: 'campaign_type',
          scopedSlots: {
            customRender: 'campaign_type'
          },
        },
        {
          title: '状态',
          width: 100,
          dataIndex: 'status',
          scopedSlots: {
            customRender: 'status'
          },
        },
        {
          title: '消耗',
          width: 100,
          dataIndex: 'cost',
          scopedSlots: {
            customRender: 'cost'
          },
        },
        {
          title: '点击',
          width: 100,
          dataIndex: 'w',
          scopedSlots: {
            customRender: 'w'
          },
        },
        {
          title: '点击率',
          width: 100,
          dataIndex: 'ctr',
          scopedSlots: {
            customRender: 'ctr'
          },
        },
        {
          title: '成单数',
          width: 100,
          dataIndex: 'm',
          scopedSlots: {
            customRender: 'm'
          },
        },
        {
          title: '成本限制',
          width: 100,
          dataIndex: 't',
          scopedSlots: {
            customRender: 't'
          },
        },
        {
          title: '复制条数',
          width: 100,
          dataIndex: 'n',
          scopedSlots: {
            customRender: 'n'
          },
        },
        {
          title: '出价调整(%)',
          width: 120,
          dataIndex: 'g',
          scopedSlots: {
            customRender: 'g'
          },
        },
        {
          title: '天数',
          width: 100,
          dataIndex: 'day',
          scopedSlots: {
            customRender: 'day'
          },
        },
        {
          title: '操作',
          width: 150,
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        },
      ],
      dataKey: 1,
      accountList: [],
      totalAccountList:[],
    }
  },
  created() {
    
  },
  methods: {
    getData() {
      this.loading = true
      strategies({task_id: this.taskId}).then((res) => {
        this.loading = false
        if (res.errcode == 0) {
          this.dataKey = 1
          for (let item of res.data) {
            item.key = this.dataKey++
            item.accountArr = item.account.split(',')
            item.xmod = 'normal'
          }
          this.dataSource = res.data
        }
      }).catch(() => {
        this.loading = false
      });
    },
    getAllBdAccountList() {
      // 获取所有账户
      getAllBdAccountList({}).then((res) => {
        if (res.errcode == 0) {
          let accountList = res.data.filter(e => e.pid != 0)
          this.totalAccountList = accountList
          this.accountList = accountList.slice(0, 100)
          // console.log(this.accountList)
        }
      }).catch(() => {
        
      });
    },
    addStrategie(item) {
      const params = {
        type: item.type,
        account: item.account,
        task_id: item.task_id,
        status: item.status,
        content: item.content,
        campaign_type:item.campaign_type,
      }
      const hideLoad = this.$message.loading('添加中')
      addStrategy(params).then((res) => {
        hideLoad()
        if (res.errcode == 0) {
          // item.xmod = 'normal'
          this.getData()
        }
      }).catch(() => {
        hideLoad()
      });
    },
    editStrategie(item) {
      const params = {
        id:item.id,
        type: item.type,
        account: item.account,
        task_id: item.task_id,
        status: item.status,
        content: item.content,
        campaign_type:item.campaign_type,
      }
      const hideLoad = this.$message.loading('更新中')
      updateStrategy(params).then((res) => {
        hideLoad()
        if (res.errcode == 0) {
          item.xmod = 'normal'
          this.getData()
        }
      }).catch(() => {
        hideLoad()
      });
    },
    deleteStrategie(id, task_id) {
      const params = {
        id,
        task_id,
      }
      const hideLoad = this.$message.loading('删除中')
      delStrategy(params).then((res) => {
        hideLoad()
        if (res.errcode == 0) {
          this.getData()
        }
      }).catch(() => {
        hideLoad()
      });
    },
    save(key) {
      let item = this.dataSource.find(e => e.key == key)
      if (this.check(item)) {
        if (item.xmod == 'add') {
          this.addStrategie(item)
        } else if (item.xmod == 'edit') {
          this.editStrategie(item)
        }
      }
    },
    close(key) {
      let item = this.dataSource.find(e => e.key == key)
      if (item.xmod == 'add') {
        let idx = this.dataSource.findIndex(e => e.key == key)
        this.dataSource.splice(idx,1)
      } else {
        item.xmod = 'normal'
      }
    },
    check(item) {
      if (!item.type) {
        this.$message.warning('请选择策略类型')
        return false
      } else {
        return true
      }
    },
    edit(key) {
      // 编辑策略
      let item = this.dataSource.find(e => e.key == key)
      item.xmod = 'edit'
    },
    addStrategieStatic() {
      // 添加策略
      this.accountList = this.totalAccountList.slice(0, 100) // 重置搜索
      let key = this.dataSource.length + 1
      this.dataSource.unshift({
        type: null,
        account: '',
        accountArr: [],
        task_id: this.taskId, 
        content: {
          cost:0,
          w:0,
          m:0,
          t:0,
          n: 0,
          g: 0,
          ctr: 0,
        },
        key: key,
        status: 1,
        xmod: 'add'
      })
    },
    accountSelect(key) {
      // 设置account
      let item = this.dataSource.find(e => e.key == key)
      item.account = item.accountArr.join(',')
    },
    cancel() {
      this.$emit('update:show', false)
    },
    accountSelectSearch(value) {
      if (value != '') {
        this.accountList = this.totalAccountList.filter(e=>e.account.indexOf(value) >= 0).slice(0, 100)
      } else {
        this.accountList = this.totalAccountList.slice(0, 100)
      }
    },
    setType(type) {
      switch (type) {
        case 1: case '1':
          return '空耗策略'
        case 2: case '2':
          return '拓量策略'
        case 3: case '3':
          return '控成本策略'
        case 4: case '4':
          return '预算策略'
        case 5: case '5':
          return '极限策略'
        case 6: case '6':
          return '批量提价'
        case 7: case '7':
          // return '笛卡尔策略'
          return '暂停策略'
        case 8: case '8':
          return '点击率策略'
        case 9: case '9':
          return '自动清理策略'
      }
    },
    setCampaign_type(type) {
      switch (type) {
        case -1: case '-1':
          return '全部计划'
        case 1: case '1':
          return '放量计划'
        case 4: case '4':
          return '控成本计划'
      }
    },
  },
  watch: {
    show(status) {
      if (status) {
        this.getData()
        this.getAllBdAccountList()
      }
    }
  },
  filters:{
    setStatus(e){
      switch(e){
        case 1: case '1':
          return '有效'
        case 0: case '0':
          return '失效'
      }
    }
  },
  components:{StandardTable}
}
</script>

<style lang="less">
.line1{
  display: block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>